<template>
  <d2-container>
  <div class="app-container">
    <el-container :style="'height:'+containerHeight+'px'">
      <el-main class="theme-front-color">
        <div class="search">
            <el-form label-position="right" :model="dataForm" :inline="true">
                 <el-form-item class="el-form-item--mini">
                    <el-input placeholder="请选择区域信息"
                      style="width: 250px;"
                      class="filter-item"
                      size="mini"
                      :suffix-icon="showTree?'el-icon-arrow-up':'el-icon-arrow-down'"
                      @click.native="deptogglePanel($event)"
                      v-model="buildingName">
                      <template slot="prepend">区域选择</template>
                    </el-input>
                    <div v-show="showTree" class="objectTree w-160" ref="suoShuMenTree">
                      <el-tree
                        :style="'height:'+containerHeight+'px'"
                        ref="buildTree"
                        highlight-current
                        node-key="buildingId"
                        :check-on-click-node="true"
                        :check-strictly="true"
                        show-checkbox
                        :data="dataList"
                        :expand-on-click-node="false"
                        :props="menuListTreeProps"
                        @check-change="selectBuild"
                        default-expand-all
                      ></el-tree>
                    </div>
                 </el-form-item>
                  <el-form-item class="el-form-item--mini">
                    <el-radio-group v-model="dataForm.dateType" size="mini">
                      <el-radio-button :label="item.date" v-for="(item, index) in Config.searchDate" :key="index">
                        {{item.label}}
                      </el-radio-button>
                    </el-radio-group>
                  </el-form-item>
                  <el-form-item label="日期" label-width="40px" class="el-form-item--mini">
                    <el-date-picker
                      v-model="dataForm.date"
                      placeholder="时间范围"
                      style="width: 200px;"
                      class="filter-item"
                      size="mini"
                      :picker-options="pickerOptions"
                      :type="dataForm.dateType"
                      suffix-icon="el-icon-date"
                      start-placeholder="开始日期"
                      end-placeholder="结束日期"
                    >
                    </el-date-picker>
                  </el-form-item>
                  <el-form-item class="el-form-item--mini">
                    <el-select v-model="dataForm.energyType"  style="width: 100px;" placeholder="请选择"  size="mini" @change="changeMeter">
                      <el-option
                        v-for="(item, index) in meterTypeList" :key="index"
                        :label="item.paramValue"
                        :value="item.paramKey">
                      </el-option>
                    </el-select>
                    </el-form-item>
                  <!--<el-form-item class="el-form-item&#45;&#45;mini">-->
                    <!--<el-button-group>-->
                      <!--<el-button v-if="showchart" size="mini" icon="el-icon-menu" @click="changeShowType">表格</el-button>-->
                      <!--<el-button v-else size="mini" icon="el-icon-picture" @click="changeShowType">图表</el-button>-->
                    <!--</el-button-group>-->
                  <!--</el-form-item>-->
                  <el-form-item class="el-form-item--mini">
                    <el-button
                      class="filter-item"
                      type="primary"
                      icon="el-icon-search"
                      size="mini"
                      @click="getPowerDataList"
                    >查询</el-button>
                    <!--<el-button-->
                        <!--class="filter-item"-->
                        <!--type="primary"-->
                        <!--icon="el-icon-download"-->
                        <!--size="mini"-->
                        <!--@click="exportExcel"-->
                    <!--&gt;导出</el-button>-->
                  </el-form-item>
            </el-form>
        </div>
        <div style="margin-top:10px;" v-if="meterTypeParamValueList.length" >
          <el-row :span="24"  :gutter="10" >
             <el-col :span="2"> <span style="font-size:15px; line-height:32px;">参数选择：</span></el-col>
              <el-col  v-for="param in meterTypeParamValueList.slice(0,7)" :key="param.id" class="show-device" :span="3">
                <span @click="changeParamSelect(param.collectType)" :class="{device:true, actived:param.collectType==currentParam}">{{param.collectName}}</span>
              </el-col>
             <el-col :span="1" style=" line-height:35px;">
              <el-button
                v-if="showParamInfo&&meterTypeParamValueList.length>7"
                class="filter-item"
                style="float:right;"
                icon="el-icon-caret-bottom"
                size="small"
                type="text"
                @click="changeParamView"
              >隐藏所有</el-button>
              <el-button
                v-if="!showParamInfo&&meterTypeParamValueList.length>7"
                class="filter-item"
                style="float:right;"
                icon="el-icon-caret-top"
                size="small"
                type="text"
                @click="changeParamView"
              >显示所有</el-button>
            </el-col>
          </el-row>
          <template v-if="showParamInfo&&meterTypeParamValueList.length>7">
              <el-row :span="24" :gutter="10" >
                <el-col :span="2">&nbsp;</el-col>
                <el-col  v-for="param in meterTypeParamValueList.slice(7)" :key="param.id" class="show-device" :span="3">
                  <span @click="changeParamSelect(param.collectType)" :class="{device:true, actived:param.collectType==currentParam}">{{param.collectName}}</span>
                </el-col>
                <el-col :span="4">&nbsp;</el-col>
              </el-row>
            </template>
        </div>
        <div style="border-bottom: solid 1px #e8e8e8;">
          <el-row :span="24"  :gutter="10" >
             <el-col :span="2"> <span style="font-size:15px; line-height:32px;">设备信息：</span></el-col>
             <el-col v-for="device in meterdataList.slice(0,7)" :key="device.id" class="show-device" :span="3">
                <span @click="changeDevice(device.meterCode)" :class="{device:true, actived:device.meterCode==currentDevice}" :title=device.deviceName>{{device.deviceName}}</span>
              </el-col>
             <el-col :span="1" style=" line-height:35px;margin-top: -25px">
              <el-button
                v-if="showDeviceInfo&&meterdataList.length>7"
                class="filter-item"
                style="float:right;"
                icon="el-icon-caret-bottom"
                size="small"
                type="text"
                @click="changeDeviceView"
              >隐藏所有</el-button>
              <el-button
                v-if="!showDeviceInfo&&meterdataList.length>7"
                class="filter-item"
                style="float:right;"
                icon="el-icon-caret-top"
                size="small"
                type="text"
                @click="changeDeviceView"
              >显示所有</el-button>
            </el-col>
          </el-row>
          <template v-if="showDeviceInfo&&meterdataList.length>7">
              <el-row :span="24" :gutter="10" >
                <el-col :span="2">&nbsp;</el-col>
                <el-col v-for="device in meterdataList.slice(7)" :key="device.id" class="show-device" :span="3">
                  <span @click="changeDevice(device.meterCode)" :class="{device:true, actived:device.meterCode==currentDevice}"  :title=device.deviceName>{{device.deviceName}}</span>
                </el-col>
                <el-col :span="1">&nbsp;</el-col>
              </el-row>
            </template>
        </div>
        <div style="margin-top:20px;" v-show="showchart">
          <div id="businessChart" class="busi-chart" :style="'height:'+chartHeight+'px;'"></div>
        </div>
        <div style="margin-top:20px;" v-show="!showchart">
          <el-table
            :data="meterTableDataList"
            border
            :height="chartHeight"
            style="width: 100%; height: 400px;overflow:auto;"
          >
            <el-table-column prop="index" header-align="center" align="center"  width="150" label="序号"></el-table-column>
            <el-table-column
              prop="buildingName"
              header-align="center"
              align="center"
              label="区域名称"
            ></el-table-column>
            <el-table-column
              prop="meterType"
              header-align="center"
              align="center"
              label="分类"
            ></el-table-column>
            <el-table-column
              prop="deviceName"
              header-align="center"
              align="center"
              label="设备名称"
            ></el-table-column>
            <el-table-column
              prop="paramName"
              header-align="center"
              align="center"
              label="参数"
            ></el-table-column>
            <el-table-column
              prop="value"
              header-align="center"
              align="center"
              :label="`用量(${unit})`"
            ></el-table-column>
            <el-table-column
              prop="dateTime"
              header-align="center"
              align="center"
              label="时间"
            ></el-table-column>

          </el-table>
        </div>
      </el-main>
    </el-container>
  </div>
  </d2-container>
</template>

<script>
import * as Util from "@/utils";
import Config from "@/utils/config"
import Minix from './mixin'
import * as Echarts from 'echarts'
export default {
  name: "device",
  mixins:[Minix],
  data() {
    return {
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() > Date.now();
        }
      },
      Config:Config,
      showTree:false,
      buildingName:'',
      dataForm: {
        date:'',
        dateType:'',
        energyType:''
      },
      page: {
        page: 1,
        total: 0,
        size: 10
      },
      menuListTreeProps: {
        label: "buildingName",
        children: "children"
      },
      dataList: [],
      showDeviceInfo: false,
      showParamInfo:false,
      currentbuildInfo: {},
      currentDevice: '',
      currentParam:'',
      businessChart:{
        name:'用电量',
        chart:"",
        x:['00','01','02','03','04','05','06','07','08','09','10','11','12','13','14','15','16','17','18','19','20','21','22','23'],
        y:[0,10240,102400,1048576,10485760],
        data:[9,7,8,5,4,6,8,9,7,8,5,4,6,8,9,7,8,5,4,6,8,3,4,2],
        title:"用电统计"
      },
      showchart:true,
      meterTypeList:[],
      meterTypeParamValueList:[],//参数列表
      meterdataList:[],//设备列表
      currentBuildNode:'',//当前选择的区域节点
      meterTableDataList:[
        // {
        //   index:'',
        //   buildingName:'',
        //   meterType:'',
        //   deviceName:'',
        //   paramName:'',
        //   dateTime:'',
        //   value:''
        // }
      ],//表格数据
      unit:'',
    };
  },
  activated() {

  },
  computed: {
    containerHeight() {
      return Util.getClientHeight() - 143;
    },
    chartHeight(){
       return Util.getClientHeight() - 373;
    }
  },
  created() {
    // this.initBarChart(this.businessChart,"businessChart");
    this.dataForm.dateType=Config.searchDate[0].date
    this.queryStatic("METER_TYPE",null,data=>{
      if (data && data.code === 0) {
        this.meterTypeList = data.page
        this.dataForm.energyType = data.page[0].paramKey;
        this.unit =this.meterTypeList.find(item=>this.dataForm.energyType==item.paramKey).paramExt;
      } else {
        this.meterTypeList = []
      }
    });
    this.getDataList();
  },
  methods: {
    /**
     * 获取参数枚举
     */
    queryStatic(type,paramValue,callback) {
      let params = {
        'code': type ,
        "customerId":this.$util.cookies.get('customer_id')
      }
      if(paramValue){
        Object.assign(params,{...paramValue});
      }
      this.$api.okhttp({
        url: this.$http.adornUrl('/sys/sysstaticdata/getList'),
        method: 'get',
        params: this.$http.adornParams(params)
      }).then((data) => {
        if(callback){
          callback(data);
        }
      });
    },
    /**
     * 获取采集分项
     */
    queryCollectType(type,paramValue,callback) {
      let params = {
        'meterType': type ,
        'state': '1' ,
        'cumulativeType':paramValue,
        "customerId":this.$util.cookies.get('customer_id'),
        'page': 1,
        'limit': 10000,
      }
      this.$api.okhttp({
        url: this.$http.adornUrl('/ecs/ecscollectitem/list'),
        method: 'get',
        params: this.$http.adornParams(params)
      }).then((data) => {
        if(callback){
          callback(data);
        }
      });
    },
    deptogglePanel (event) {
      event || (event = window.event)
      event.stopPropagation
        ? event.stopPropagation()
        : (event.cancelBubble = true)
      this.showTree ? this.dephide() : this.depshow()
    },
    depshow () {
      this.showTree = true
      document.addEventListener('click', this.dephidePanel, false)
    },
    dephide () {
      this.showTree = false
      document.addEventListener('click', this.dephidePanel, false)
    },
    dephidePanel (e) {
      if (
        this.$refs.suoShuMenTree &&
        !this.$refs.suoShuMenTree.contains(e.target)
      ) {
        this.dephide()
      }
    },
    //根据区域查询设备列表
    getmeterDataList(buildingId) {
      if(this.businessChart.chart!=='' ){
        this.businessChart.chart = Echarts.init(document.getElementById('businessChart'))
        this.businessChart.chart.clear()
      }

      this.$api.okhttp({
        url: this.$http.adornUrl("/ecs/ecsbuildingmeter/list"),
        method: "get",
        params: this.$http.adornParams({
          page: 0,
          limit: 1000,
          buildingId: buildingId,
          meterType: this.dataForm.energyType,
          'projectId': this.$util.cookies.get("cuuren_projectId"),
          customerId: this.$util.cookies.get("customer_id")
        })
      }).then((data) => {
        if (data && data.code === 0&&data.page.list.length>0) {
          this.meterdataList = data.page.list;
          //默认设为第一个选中
          this.currentDevice=this.meterdataList.length?this.meterdataList[0].meterCode:''
          this.getPowerDataList();
        } else {
          this.meterdataList = [];
        }
      });
    },
    selectBuild (data, checked, indeterminate) {
      if(checked){
        this.$refs.buildTree.setCheckedNodes([]);
        this.buildingName = data.buildingName;
        this.currentBuildNode = data;
        //查询设备列表
        this.getmeterDataList(data.buildingId);
        this.$refs.buildTree.setChecked(data.buildingId,checked);
        this.showTree = false
      }
    },
    // 获取数据列表
    getDataList() {
      this.$api.okhttp({
        url: this.$http.adornUrl("/ecs/ecsbuildinginfo/select"),
        method: "get",
        params: this.$http.adornParams({
          page: this.page.pageIndex,
          limit: this.page.pageSize,
          key: this.dataForm.key,
          customerId: this.$util.cookies.get("customer_id"),
          projectid:this.$util.cookies.get("cuuren_projectId")
        })
      }).then((data) => {
        if (data && data.code === 0) {
          if(data.menuList.length>0){
            this.currentBuildNode = data.menuList.find(item=>item.buildingId!==-1),
            //默认选择区域
            this.selectBuild(this.currentBuildNode,true);
          }
          this.dataList = Util.treeDataTranslate(
            data.menuList,
            "buildingId",
            "parentBuildingId"
          );
        } else {
          this.dataList = [];
        }
      });
    },
    changeShowType(){
      this.showchart = !this.showchart;
    },
    initBarChart(opt,obj,unit){
      let option={
          grid:{
              x:50,
              y:30,
              x2:25,
              y2:25,
              left:30
          },
          title:{
              text:opt.title,
              show:true,
              left:'center',
              textStyle:{
                  color:"#ccc",
                  fontSize:14,
                  fontFamily:"MicrosoftYaHei",
                  lineHeight:14,
              },
              padding:0,
          },
          legend:{
            show:true,
            right:30,
            top:-5,
            data:[{
                name: opt.name,
                // 强制设置图形为圆。
                icon: 'circle',
            }],
          },
          tooltip: {
              trigger: 'item',
              formatter: '{a}:{c}'+unit
          },
          xAxis:{
              type:'category',
              data:opt.x,
              axisLine:{
                  lineStyle:{
                      color:"#2C73D2",
                      type:'solid',
                      width:0.5
                  },
              },
              axisLabel:{
                  color:"#ccc",
                  interval:0,
              },
              axisTick: {
                  show:false,
                  alignWithLabel: true
              }
          },
          yAxis:{
              name:'单位:'+unit,
              nameTextStyle:{
                align:'left',
              },
              type:'value',
              data:opt.y,
              axisLabel:{
                  color:"#ccc",
              },
              axisLine:{
                  lineStyle:{
                      color:"#ccc",
                      type:'soild',
                      opacity:0,
                  }
              },
              axisLabel:{
                  formatter:function(value,index){
                    return value;
                  }
              },
              axisTick: {
                  show:false,
                  alignWithLabel: true
              },
              splitLine:{
                  lineStyle:{
                      color:"#2C73D2",
                      type:"dotted",
                      opacity:0.5,
                  }
              },
          },
          series: [{
            name:opt.name,
            type: 'bar',
            barWidth: "60%",
            data: opt.data,
            itemStyle:{
                normal: {
                  barBorderRadius:[14,14,0,0],
                },
            }
          }],
          color:['#4C7EDF','#FFCC00', '#00CC33', '#D05454',]
      }
      opt.chart = Echarts.init(document.getElementById(obj));
      opt.chart.setOption(option);
    },
    changeDevice(id) {
      this.currentDevice = id;
      this.getPowerDataList()
    },
    changeParamSelect(key){
      this.currentParam= key;
      this.getPowerDataList()
    },
    getPowerDataList() {
      //查询数据
      //需要将日期格式化
      let date= (this.dataForm.date&&this.dataForm.date!="")?this.formarDate(this.dataForm.dateType,new Date(this.dataForm.date)):''
      let params = {
          // customerId: "115",
          // date: "20200429",
          // dateType: "1",
          // meterCode: "3",
          // meterType: "1",
          // paramValue: "1",

          customerId: this.$util.cookies.get("customer_id"),
          dateType:Config.searchDate.find(item=>item.date==this.dataForm.dateType).typeDesc,//1日2月3年
          date:date,
          meterCode:this.currentDevice,//设备编码
          meterType:this.dataForm.energyType,//分类type
          paramValue:this.currentParam
      }
      this.$api.okhttp({
        url: this.$http.adornUrl('/ecm/device/list'),
        method: 'post',
        data: this.$http.adornData(params)
      }).then((data) => {
        if (data && data.code === 0) {
        this.handleDataList(data.data)
        }
      });
    },
    changeDeviceView() {
      this.showDeviceInfo = !this.showDeviceInfo;
    },
    changeParamView(){
      this.showParamInfo=!this.showParamInfo
    },
    sizeChangeHandle(size) {},
    currentChangeHandle(page) {},
    //处理图形上的数据
    handleDataList(data){
      let self=this
      this.businessChart={
        chart:"",
        name:`用${this.meterTypeList.find(item=>item.paramKey==this.dataForm.energyType).paramValue}量`,
        x:[],
        y:[],
        data:[],
        title:`用${ this.meterTypeList.find(item=>item.paramKey==this.dataForm.energyType).paramValue}统计`
      }
      this.meterTableDataList=[]
      let meterTypeName=this.meterTypeList.find(item=>item.paramKey==this.dataForm.energyType).paramValue||''
      let deviceName=this.meterdataList.find(item=>item.meterCode==this.currentDevice).deviceName||''
      let paramName=this.meterTypeParamValueList.length?this.meterTypeParamValueList.find(item=>item.collectType==this.currentParam).collectName:''
      data.forEach((element,index) => {
        this.businessChart.x.push(element.dateDetail)
        this.businessChart.data.push(element.val)
        //处理表格数据
        this.meterTableDataList.push({
          index:index+1,
          buildingName:this.buildingName,
          meterType:meterTypeName,
          deviceName:deviceName,
          paramName:paramName,
          dateTime:this.dataForm.dateType=='date'?element.date+' '+element.dateDetail+'H':element.date+'-'+element.dateDetail,
          value:element.val
        })

      });
      this.initBarChart(this.businessChart,"businessChart",this.unit);
    },
    exportExcel(){
      let header=['序号','区域名称','分类','设备名称','参数','时间',`用量(${this.unit})`]
      let props=['index','buildingName','meterType','deviceName','paramName','dateTime','value']
      let fileName=`用${ this.meterTypeList.find(item=>item.paramKey==this.dataForm.energyType).paramValue}统计`
      this.export2Excel(header,props,fileName,this.meterTableDataList)
    },
    export2Excel (tH, fi, fiNa, dataList) {
      var tHeader = tH
      var filterVal = fi
      var fileName = fiNa
      require.ensure([], () => {
        const {export_json_to_excel} = require('@/utils/Export2Excel.js')
        const list = dataList
        const data = this.formatJson(filterVal, list)
        export_json_to_excel(tHeader, data, fileName)
      })
    },
    formatJson (filterVal, jsonData) {
      return jsonData.map(v => filterVal.map(j => v[j]))
    },
    changeMeter(){
      this.getmeterDataList(this.currentBuildNode.buildingId);
    }
  },
  watch:{
    'dataForm.energyType':function (newValue,oldValue){
      // 重新查一下参数列表
      //查参数选择时传   keyType:'1',
      this.queryCollectType(this.dataForm.energyType,'1',data=>{
        if (data && data.code === 0) {
          this.meterTypeParamValueList = data.page.list
          //默认参数选择
          this.currentParam=this.meterTypeParamValueList.length?this.meterTypeParamValueList[0].collectType:''
          this.unit =  this.meterTypeParamValueList.length>0?
          this.meterTypeParamValueList.find(item=>item.collectType==this.currentParam).collectUnit:
          this.meterTypeList.find(item=>this.dataForm.energyType==item.paramKey).paramExt;
        } else {
          this.meterTypeParamValueList = [];
          this.unit =  this.meterTypeParamValueList.length>0?
          this.meterTypeParamValueList.find(item=>item.collectType==this.currentParam).collectUnit:
          this.meterTypeList.find(item=>this.dataForm.energyType==item.paramKey).paramExt;
        }
      });

    },
  }
};
</script>
<style scoped>
  .el-tree{
    min-width: 110%;
    display:inline-block;
  }
  .search{
    padding: 20px 0px 5px 0px;
    border: 1px solid #f9f5f5;
    border-left: none;
    border-right: none;
  }
  .el-form-item--medium .el-form-item__content, .el-form-item--medium .el-form-item__label{
    line-height: 27px;;
  }
  .device {
    /*display: inline-block;*/
    padding: 0 10px;
    /*line-height: 30px;*/
    /*color: #8a8c8e;*/
    /*!* border: 1px solid #d9ecff; *!*/
    /*border-radius: 4px;*/
    /*-webkit-box-sizing: border-box;*/
    /*box-sizing: border-box;*/
    /*white-space: nowrap;*/
    /*overflow: hidden;*/
    /*text-overflow: ellipsis;*/

    display :inline-block ;width: 100%;overflow: hidden;textOverflow: ellipsis;whiteSpace: nowrap
  }
  .actived {
    border: 1px solid #678af4;
    color: #678af4;
  }
  .show-device {
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    line-height: 30px;
    cursor: pointer;
    padding-right: 20px;
  }
  .tree-area { background-color: rgba(0, 0, 0, 0.1);
    width: 200px !important;
    /* box-shadow: 0px 0px 2px 2px #f7f6f6; */
    padding-top: 10px;
  }
  .bg-white {
    box-shadow: 0px 0px 2px 2px #f7f6f6;
  }
  .el-tree-node__content {
    height: 30px !important;
  }
  .busi-chart{
      width: 100%;
      height: 400px;
      margin-top: 10x;
  }
  .objectTree {
      margin-left: 89px;
      position: absolute;
      overflow: auto;
      z-index: 100;
      height: 200px;
      /* border: 1px solid #ddd; */
      line-height: normal;
      z-index: 204;
      box-shadow: 0px 0px 1px 1px #e2dfdf;
      margin-top: 3px;
      border-radius: 4px;
    background-color: white;
  }
  .w-160{
    width: 160px
  }
</style>
